import React, {useState, useContext} from 'react';
import { PoloContext } from "@marvintau/poloscope";

import {Input} from 'reactstrap';

import './filter.css'
import {ReactComponent as CreateRecordIcon} from './create-record.svg';

const FilterCol = ({colKey, isFilterable, isSortable, filterCol, sortCol, width, editControl, editMethods, ...colProps}) => {

  const {refreshItem} = useContext(PoloContext);

  const [inputVal, setInputVal] = useState('');

  if (editControl) {

    const {insert} = editMethods;

    const handler = (e) => {
      e.preventDefault();
      e.stopPropagation();
      insert(0);
      refreshItem(0);
    }  

    return <div className="edit-button-line filter-col" style={{width}} {...colProps}>
      <div className="edit-button" onClick={handler}><CreateRecordIcon /></div>
    </div>
  
  } else {

    const SortComp = <div
      className="sort-button"
      style={{marginLeft: 'auto'}}
      onClick={() => sortCol(colKey)}
    >排序</div>;

    const FilterComp = <Input
      className='filter-input'
      bsSize="sm"
      value={inputVal}
      onChange={(e) => setInputVal(e.target.value)}
      onKeyPress={(e) => {
        (e.key === 'Enter') && filterCol(colKey, inputVal);
    }} />;

    return <div className="filter-col" style={{width}} {...colProps} >
      {isFilterable && FilterComp}
      {isSortable && SortComp}
    </div>

  }
}

export default (cols, editMethods) => {

  if(Object.values(cols).every(({isFilterable}) => !isFilterable)){
    return () => <div className="filter-row"></div>;
  }

  return ({filterCol, sortCol}) => {

    const colsElem = Object.entries(cols).map(([key, spec]) => {
      const colProp = {
        ...spec,
        colKey: key,
        sortCol,
        filterCol,
        editMethods,
      }
      return <FilterCol key={key} {...colProp} />
    });
  
    return <div className="filter-row">{colsElem}</div>
  }
}